package controllers

import (
	"encoding/json"
	"time"

	"gitee.com/lzqysoft/ga_wz_backend/libs/aes"
	"gitee.com/lzqysoft/ga_wz_backend/libs/encrypt"
	"gitee.com/lzqysoft/ga_wz_backend/libs/strtool"

	//	"strconv"
	m "gitee.com/lzqysoft/ga_wz_backend/models"

	"github.com/astaxie/beego"
)

//CommonController 自定义通用controller
type CommonController struct {
	beego.Controller
	IsLogin     bool
	TokenString string
	User        *m.User
}

// var Ssdbp libs.SsdbProvider

//init 初始化检查权限
// 针对过滤的url进行验证
func init() {
	// beego.InsertFilter("/ilive/*", beego.BeforeRouter, Check)
}

//Jdata 返回客户端数据结构
//正确code：0，Status：200
type Jdata struct {
	Code    int         `json:"code"`
	Token   string      `json:"token"`
	Message string      `json:"message"`
	Jdata   interface{} `json:"jdata"` //返回数据。加密
}

type PageData struct {
	PageSize  int64             `json:"pagesize"`
	Page      int64             `json:"page"`
	SearchKey string            `json:"searchKey"`
	SortBy    []string          `json:"sortby"`
	Order     []string          `json:"order"`
	Fields    []string          `json:"fields"`
	Query     map[string]string `json:"query"`
}

//Prepare 准备方法
//获取用户信息,判断登录,更新活动日志
func (c *CommonController) Prepare() {
	// Setting properties.
	user, ts:= c.GetUserinfo()
	c.User = user
	c.IsLogin = true
	c.TokenString = ts
	//	c.Dlog("活动日志：访问了"+c.Ctx.Input.URL(), user.Id, 3)
	//	userprof, _ := m.GetUserprofById(user.Id)
	// user.Activecount = user.Activecount + 1
	// user.Loginip = c.Ctx.Input.IP()
	// user.Logintime = time.Now()
	// m.UpdateUserById(user)
}

//RetError json格式返回错误码.
func (c *CommonController) RetError(e *ControllerError) {
	if mode := beego.AppConfig.String("runmode"); mode == "prod" {
		e.DevInfo = ""
	}
	//	base.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
	//	base.Ctx.Output.Header("Content-Encoding", "gzip")
	c.Ctx.ResponseWriter.WriteHeader(e.Status)
	beego.Debug("返回错误:", e)
	c.Data["json"] = e
	c.ServeJSON()
	c.StopRun()
}

//RetSuccess json格式返回正确值
// 返回tokens则采用token,否则直接获取Controller中的token
func (c *CommonController) RetSuccess(data interface{}, tokens ...string) {
	//	base.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
	//	base.Ctx.ResponseWriter.WriteHeader(e.Status)
	//adata, err := c.AesEncode(data)
	adata, err:=json.Marshal(data)
	if err != nil {
		c.RetError(ErrAes)
	}
	var jdata Jdata
	if len(tokens) > 0 {
		jdata.Token = tokens[0]
	} else {
		jdata.Token = c.TokenString
	}
	jdata.Code = 0
	jdata.Message = "操作成功"
	jdata.Jdata = string(adata)
	c.Data["json"] = jdata
	c.ServeJSON()
	c.StopRun()
}

//Dlog 写入日志
//tp :登录为2,普通为1,第二个参数可以是旧数据对象
func (c *CommonController) Dlog(opa string, oid string, tp ...interface{}) error {
	var log m.Log
	user, _:=c.GetUserinfo()
	log.UserId = user.Id
	log.Lon = 0
	log.Lat = 0
	log.Address = "-"
	log.UserName = user.Name
	switch len(tp) {
	case 0:
		log.Type = 1
	case 1:
		log.Type = tp[0].(int)

	case 2:
		log.Type = tp[0].(int)
		od, _:=json.Marshal(tp[1])
		log.Olddata = string(od)

	}
	log.Id = encrypt.GetGuid()
	log.Ip = c.Ctx.Input.IP()
	org, err:=m.GetOrganizationById(user.Organization.Id)
	if err != nil {
		c.RetError(ErrNoUser)
	}

	log.OrgId = org.Id
	log.OrgName = org.Name
	log.Contect = log.UserName + ",操作为" + opa + ", id 为：" + oid
	log.Status = 1
	log.Creater = log.UserName
	log.Ctime = time.Now()

	log.Updater = log.Creater
	log.Utime = log.Ctime
	// beego.Debug(log.Ctime)
	_, err = m.AddLog(&log)
	return err
}

//AesEncode json数据aes加密
func (c *CommonController) AesEncode(plantText interface{}) (string, error) {
tokenstring:=c.Ctx.Input.Header("Authorization")
key:=[]byte(strtool.Substr(tokenstring, 5, 16))
	jp, _:=json.Marshal(plantText)
	v, err:=aes.AesEncrypt(jp, key, key)
	return v, err
}

//AesDecode json数据aes解密返回interface{}
func (c *CommonController) AesDecode(cipherstring string) (interface{}, error) {
	// tokenstring:=c.Ctx.Input.Header("Authorization")
	// if len(cipherstring) < 1 {
	// 	return nil, errors.New("数据为空")
	// }
	bc:=[]byte(cipherstring)
	// beego.Debug(cipherstring)
	// key := []byte(strtool.Substr(tokenstring, 5, 16))
	// v, err := aes.AesDecrypt(cipherstring, key, key)
	var s interface{}
	err:=json.Unmarshal(bc, &s)

	return s, err
}

//AesDecodeToByte json数据aes解密为[]byte
func (c *CommonController) AesDecodeToByte(cipherstring string) ([]byte, error) {
	//tokenstring := c.Ctx.Input.Header("Authorization")
	////	bc := []byte(cipherstring)
	//key := []byte(strtool.Substr(tokenstring, 5, 16))
	//v, err := aes.AesDecrypt(cipherstring, key, key)
	//return v, err
res:=[]byte(cipherstring)
	return res, nil
}

//GetUserinfo 获取用户信息
func (c *CommonController) GetUserinfo() (*m.User, string) {
	jcliem, ts, err:=c.Getjwt()
	if err != nil {
		c.RetError(ErrToken)
	}
uid:=jcliem.Userid
	user, err:=m.GetUserById(uid)
	if err != nil {
		c.RetError(ErrNoUser)
	}
	return user, ts
}
